import React, { useState, useEffect } from 'react';
import { Button, Toast, Modal } from 'antd-mobile';
import { UserContactOutline } from 'antd-mobile-icons';
import Loading from './components/Loading.jsx';
import UserAgreement from './components/UserAgreement.jsx';
import { useAuth } from './context/AuthContext.jsx';
import { createOrder, payOrder, mockLogin } from './server/api';

const plans = [
  {
    code: 'monthly',
    name: '一个月',
    price: '9.9元',
    description: '不满意可退',
    recommended: true,
    save: null,
  },
  {
    code: 'yearly',
    name: '一年',
    price: '19.9元',
    description: '永久免费更新',
    save: '98.9',
  },
  {
    code: 'lifetime',
    name: '永久',
    price: '29.9元',
    description: '24H在线售后',
    save: '178.9',
  },
];

const PlanItem = ({ plan, selected, onClick }) => (
  <div
    onClick={onClick}
    style={{
      border: `1.5px solid ${selected ? '#16C05D' : '#f0f0f0'}`,
      borderRadius: '8px',
      padding: '15px',
      position: 'relative',
      background: selected ? '#f0fff8' : 'white',
      marginBottom: '12px',
      cursor: 'pointer',
    }}
  >
    {plan.recommended && (
      <div
        style={{
          position: 'absolute',
          top: 0,
          right: 0,
          background: '#16C05D',
          color: 'white',
          padding: '2px 6px',
          fontSize: '10px',
          borderTopRightRadius: '8px',
          borderBottomLeftRadius: '8px',
        }}
      >
        推荐
      </div>
    )}
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
      }}
    >
      <div style={{ textAlign: 'left' }}>
        <span style={{ fontWeight: 'bold', fontSize: '16px' }}>
          {plan.name}
        </span>
        <span style={{ margin: '0 8px', color: '#ccc' }}>|</span>
        <span style={{ color: '#888', fontSize: '14px' }}>
          {plan.description}
        </span>
        <div
          style={{
            color: '#e54d42',
            fontWeight: 'bold',
            fontSize: '18px',
            marginTop: '8px',
          }}
        >
          {plan.price}
        </div>
      </div>
      <div
        style={{
          width: '20px',
          height: '20px',
          borderRadius: '50%',
          border: `1.5px solid ${selected ? '#16C05D' : '#ccc'}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {selected && (
          <div
            style={{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              background: '#16C05D',
            }}
          ></div>
        )}
      </div>
    </div>
    {plan.save && (
      <div
        style={{
          position: 'absolute',
          bottom: '8px',
          right: '8px',
          background: '#ffeded',
          color: '#e54d42',
          padding: '2px 6px',
          fontSize: '10px',
          borderRadius: '4px',
        }}
      >
        省¥{plan.save}元
      </div>
    )}
  </div>
);

function App() {
  const [selectedPlan, setSelectedPlan] = useState('monthly');
  const [agreementVisible, setAgreementVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [loadingTitle, setLoadingTitle] = useState('正在开启消息已读功能');
  const [loadingSubtitle, setLoadingSubtitle] = useState('正在检测消息数据...');
  const [progress, setProgress] = useState(0);
  const { auth, setAuth } = useAuth();

  // 页面加载时执行登录
  useEffect(() => {
    let loginFinished = false;
    let stepsFinished = false;

    const finishLoading = () => {
      if (loginFinished && stepsFinished) {
        setProgress(100);
        setLoadingTitle('准备就绪');
        setLoadingSubtitle('即将进入会员开通页面');
        setTimeout(() => setIsLoading(false), 800);
      }
    };

    // 1. 检查是否是微信授权回调
    const checkWechatCallback = () => {
      const urlParams = new URLSearchParams(window.location.search);
      const token = urlParams.get('token');
      const nickname = urlParams.get('nickname');
      const avatar = urlParams.get('avatar');
      const id = urlParams.get('id');
      const isVipParam = urlParams.get('isVip');

      if (token && nickname) {
        // 从 URL 参数中恢复用户信息
        console.log('=== 检测到微信授权回调 ===');
        const userInfo = {
          id: id ? Number(id) : undefined,
          token,
          nickname: decodeURIComponent(nickname),
          avatar: avatar || '',
          isVip: String(isVipParam).toLowerCase() === 'true',
        };
        setAuth({ token, userInfo });
        // 保存 token 到 localStorage
        localStorage.setItem('token', token);
        console.log('微信登录成功，用户信息:', userInfo);

        // 清除 URL 参数
        window.history.replaceState({}, '', window.location.pathname + window.location.hash);
        return true;
      }
      return false;
    };

    // 2. 执行登录逻辑
    const performLogin = async () => {
      try {
        // 优先检查是否是微信回调（已拿到用户信息）
        if (checkWechatCallback()) {
          loginFinished = true;
          finishLoading();
          return;
        }

        // 检查是否在微信浏览器中
        const isWechat = /MicroMessenger/i.test(navigator.userAgent);
        // 只在本地开发时使用模拟登录（localhost 或 127.0.0.1）
        const isLocalDev = window.location.hostname === 'localhost' ||
                          window.location.hostname === '127.0.0.1';

        if (isWechat && !isLocalDev) {
          // 微信环境（包括微信开发者工具），跳转到微信授权
          console.log('=== 检测到微信浏览器，跳转到授权页面 ===');
          const authUrl = `${window.location.origin}/api/wechat/auth`;
          console.log('授权地址:', authUrl);
          window.location.href = authUrl;
          return;
        }

        // 本地开发环境或非微信浏览器，使用模拟登录（拿到用户信息后再结束加载）
        console.log('=== 开发环境，使用模拟登录 ===');
        const response = await mockLogin();
        console.log('登录接口返回:', response);
        if (response) {
          console.log('准备设置 auth，数据:', response);
          setAuth(response);
          // 保存 token 到 localStorage
          localStorage.setItem('token', response.token);
          console.log('模拟登录成功，用户信息:', response.userInfo);
          loginFinished = true;
          finishLoading();
        }
      } catch (error) {
        console.error('Login failed:', error);
        Toast.show({ icon: 'fail', content: '登录失败，请刷新重试' });
      }
    };
    performLogin();

    // 2. 执行加载动画
    const loadingSteps = [
      { text: '已读功能初始化...', progress: 20 },
      { text: '正在配置消息提醒...', progress: 40 },
      { text: '优化消息显示效果...', progress: 60 },
      { text: '已读功能即将开启...', progress: 80 },
    ];
    let stepIndex = 0;
    const interval = setInterval(() => {
      if (stepIndex < loadingSteps.length) {
        const currentStep = loadingSteps[stepIndex];
        setLoadingSubtitle(currentStep.text);
        setProgress(currentStep.progress);
        stepIndex++;
      } else {
        clearInterval(interval);
        stepsFinished = true;
        finishLoading();
      }
    }, 800);

    return () => clearInterval(interval);
  }, [setAuth]);

  useEffect(() => {
    if (agreementVisible) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, [agreementVisible]);

  const user = auth.userInfo;

  // 调试：监听 auth 变化
  useEffect(() => {
    console.log('=== App.jsx Auth 状态更新 ===');
    console.log('完整 auth 对象:', auth);
    console.log('用户信息:', user);
  }, [auth, user]);

  const handlePayment = async () => {
    console.log('=== 点击支付按钮 ===');
    console.log('当前 auth:', auth);
    console.log('当前用户:', user);
    if (!user) {
      Toast.show({ content: '正在获取用户信息，请稍候...' });
      return;
    }
    try {
      // 1. 创建订单
      Toast.show({ icon: 'loading', content: '正在创建订单...', duration: 0 });
      const order = await createOrder({
        planCode: selectedPlan,
        userId: user.id,
      });
      console.log('订单创建成功:', order);

      // 2. 调用支付接口
      Toast.show({ icon: 'loading', content: '正在发起支付...', duration: 0 });
      const payParams = await payOrder({ orderId: order.id });
      console.log('支付参数:', payParams);

      // 3. 调用微信 JSAPI 支付
      if (typeof WeixinJSBridge === 'undefined') {
        Toast.show({ icon: 'fail', content: '请在微信客户端中打开' });
        return;
      }

      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: payParams.appId,
          timeStamp: payParams.timeStamp,
          nonceStr: payParams.nonceStr,
          package: payParams.package,
          signType: payParams.signType,
          paySign: payParams.paySign,
        },
        function (res) {
          Toast.clear();
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            Toast.show({ icon: 'success', content: '支付成功！' });
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            Toast.show({ content: '支付已取消' });
          } else {
            Toast.show({ icon: 'fail', content: '支付失败，请重试' });
          }
        }
      );
    } catch (error) {
      Toast.clear();
      Toast.show({ icon: 'fail', content: `操作失败: ${error.message}` });
    }
  };

  // 如果正在加载，显示加载动画
  if (isLoading) {
    return (
      <Loading
        title={loadingTitle}
        subtitle={loadingSubtitle}
        progress={progress}
      />
    );
  }

  return (
    <div style={{ background: '#f7f8fa', minHeight: '100vh', padding: '16px' }}>
      <div
        style={{
          background: 'white',
          padding: '20px',
          borderRadius: '12px',
          textAlign: 'center',
        }}
      >
        <h2 style={{ fontSize: '22px', fontWeight: 'bold', margin: '10px 0' }}>
          开通已读功能
        </h2>
        <p style={{ color: '#888', marginBottom: '24px' }}>
          不用再猜，发完立刻知道对方看没看
        </p>

        <div>
          {plans.map((plan) => (
            <PlanItem
              key={plan.code}
              plan={plan}
              selected={selectedPlan === plan.code}
              onClick={() => setSelectedPlan(plan.code)}
            />
          ))}
        </div>

        <Button
          block
          size="large"
          style={{
            marginTop: '20px',
            '--background-color': '#16C05D',
            '--border-color': '#16C05D',
            '--text-color': 'white',
            fontWeight: 'bold',
            fontSize: '16px',
          }}
          onClick={handlePayment}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
            }}
          >
            <UserContactOutline />
            <span>立即开通</span>
          </div>
        </Button>

        <p style={{ color: '#aaa', fontSize: '12px', marginTop: '15px' }}>
          点击支付即代表您同意
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              setAgreementVisible(true);
            }}
            style={{ color: '#16C05D', textDecoration: 'none' }}
          >
            《用户服务协议》
          </a>
        </p>
        <p style={{ color: '#ccc', fontSize: '12px', marginTop: '20px' }}>
          &lt;&lt;&lt; 兼职赚 🧧 &gt;&gt;&gt;
        </p>
      </div>
      <div
        style={{
          textAlign: 'center',
          color: '#ccc',
          fontSize: '12px',
          padding: '20px 0',
        }}
      >
        微信·版本 8.0.60
      </div>

      <Modal
        visible={agreementVisible}
        title="用户协议"
        style={{ '--width': '90vw' }}
        content={<UserAgreement />}
        closeOnAction
        onClose={() => setAgreementVisible(false)}
        actions={[
          {
            key: 'confirm',
            text: '关闭',
            style: { color: '#16C05D' },
          },
        ]}
      />
    </div>
  );
}

export default App;
